package com.task.servlet;

import com.alibaba.fastjson.JSON;
import com.task.exception.CommonException;
import com.task.model.TaskModel;
import com.task.util.DispatcherManager;
import com.task.util.HttpRequestUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "FileServlet",urlPatterns = "/fileList")
public class FileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，前端后台统一是utf-8
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

        String fileName= request.getParameter("filename");

        /****** 文件路径部分 用的是项目发布的相对路径******/
        // Servlet上下文对象
        ServletContext servletContext = this.getServletConfig().getServletContext();
        // tomcat的项目路径，记住要加斜杠
        File file=new File(this.getClass().getResource("/").getPath()+ "files/");

        String realPath = file.getPath();
        String filePath = realPath+"/"+fileName+".jpg";//合起来就是完整的文件路径了
        System.out.println("UploadTestServlet filePath:"+filePath);
        File realPathFile = new File(realPath);
        if (!realPathFile.exists()) {
            realPathFile.mkdirs();
        }

        /****** 读写部分  ******/
        FileOutputStream fos = new FileOutputStream(new File(filePath));
        //传给页面的输出流
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;;
        while ((len=sis.read(b))!=-1) {
            fos.write(b, 0, len);
        }

        /****** 关闭资源  ******/
        fos.close();
        sis.close();

        response.sendRedirect(request.getContextPath()+"/fileManager.html");


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File file=new File(this.getClass().getResource("/").getPath()+ "files/");

        String[] fileList=file.list();
        try {
            HttpRequestUtils.responseJSON(JSON.toJSONString(fileList),response);
        } catch (CommonException e) {
            e.printStackTrace();
        }
    }
}
